<?php

namespace App\Exceptions;

use App\Services\IpBlacklistService;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Throwable;

class Handler extends ExceptionHandler
{
    public function report(Throwable $exception)
    {
        parent::report($exception);
    }

    public function render($request, Throwable $exception)
    {
        // 如果是某些特定异常，将 IP 加入黑名单
        if ($this->shouldAddToBlacklist($exception)) {
            app(IpBlacklistService::class)->addToBlacklist(
                $request->ip(),
                config('ip_blacklist.ban_duration', 60)
            );
            
            // 记录异常访问
            app(IpBlacklistService::class)->logAccess(
                $request->ip(), 
                $request->path(), 
                'exception: ' . get_class($exception)
            );
        }

        return parent::render($request, $exception);
    }

    /**
     * 判断是否需要将 IP 加入黑名单
     */
    protected function shouldAddToBlacklist(Throwable $exception)
    {
        $blacklistExceptions = [
            \Illuminate\Auth\AuthenticationException::class,
            \Illuminate\Auth\Access\AuthorizationException::class,
            \Symfony\Component\HttpKernel\Exception\HttpException::class,
        ];

        foreach ($blacklistExceptions as $blacklistException) {
            if ($exception instanceof $blacklistException) {
                return true;
            }
        }

        return false;
    }
}
